package com.bnz.servlet;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.bnz.pojo.PageResult;
import com.bnz.pojo.Student;
import com.bnz.service.StudentService;
import com.bnz.service.impl.StudentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/student")
public class StudentServlet extends HttpServlet {

    private StudentService studentService = new StudentServiceImpl();

    /**
     * 1. 初始化StudentServiceImpl
     * @throws ServletException
     */
    @Override
    public void init() throws ServletException {
        studentService = new StudentServiceImpl();
    }

    /**
     * 2. 根据请求参数cmd路由更换
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //3.0 指定响应页面的字符集编码
        resp.setContentType("text/html;charset=utf-8");
        //2.1 得到请求参数
        String cmd = req.getParameter("cmd");
        //2.2 根据参数调用不同的方法
        if (StrUtil.isNotBlank(cmd)){
            if ("list".equals(cmd)){
                list(req,resp);
            }if ("findByPage".equals(cmd)){
                findByPage(req,resp);
            }
        }

    }

    /**
     * 3. 列表学生
     * @param req
     * @param resp
     */
    private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //3.1 查询所有学生
        List<Student> students = studentService.findAll();
        //3.2 把学生集合转成json串
        String s = JSON.toJSONString(students);
        //3.3 输出内容到页面上
        resp.getWriter().println(s);
        //3.4 刷新页面
        resp.getWriter().flush();
    }

    /**
     * 4. 分页查询
     * @param req
     * @param resp
     */
    private void findByPage(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //4.1 得到查询分页
        int page = new  Integer(req.getParameter("page"));
        int pagesize = new Integer(req.getParameter("pagesize"));
        //4.2 开始分页查询
        PageResult<Student> pr = studentService.findByPage(page,pagesize);
        //4.3 把学生集合转成json串
        String s = JSON.toJSONString(pr);
        //4.4 输出内容到页面上
        resp.getWriter().println(s);
        //4.5 刷新页面
        resp.getWriter().flush();

    }

}
